<template>
  <div>
    <c-table-box
      ref="cTableBox"
      hide-func
      checkbox
      :no-request="noRequest"
      :other-filters="otherFilters"
      :table-config="tableConfig"
      @selection-change="selectionChange"
    >
      <template #btn>
        <c-permission v-if="type==='all'" code="all">
          <c-button opt-code="add" type="primary" @click="handleEdit('1')">新增</c-button>
          <c-button opt-code="export" type="primary" @click="handleExport">导出</c-button>
        </c-permission>
        <c-permission v-if="type==='submit'" code="submit">
          <c-button opt-code="edit" type="primary" @click="handleEdit('2')">编辑</c-button>
          <c-button opt-code="submit" type="primary" @click="handleSubmit">提交</c-button>
          <c-button opt-code="termination" type="primary" @click="handleTeminal">终止</c-button>
          <c-button opt-code="export" type="primary" @click="handleExport">导出</c-button>
        </c-permission>
        <c-permission v-if="type==='audit'" code="audit">
          <c-button opt-code="audit" type="primary" @click="handleAudit">审核</c-button>
          <c-button opt-code="export" type="primary" @click="handleExport">导出</c-button>
        </c-permission>
        <c-permission v-if="type==='fileMaintenance'" code="fileMaintenance">
          <c-button opt-code="fileMaintenance" type="primary" @click="handlefileMain">档案维护</c-button>
          <c-button opt-code="export" type="primary" @click="handleExport">导出</c-button>
        </c-permission>
      </template>

    </c-table-box>
    <export-files v-if="exportVisible" title="导出" :config="exportAllConfig" :visible.sync="exportVisible" @success="handleExportSuccess" />
    <!-- 审核弹窗 -->
    <el-dialog
      ref="refDlg"
      :visible.sync="auditVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="clearForm"
      width="450px"
      @close="closeDialog"
    >
      <el-form ref="refForm" :rules="auditRules" :model="formData" size="mini" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="审核结果:" prop="reviewResult">
              <el-select
                v-model="formData.reviewResult"
                placeholder="请选择"
                style="width: 100%"
                @change="changeresult"
              >
                <el-option
                  v-for="item in auditOptions"
                  :key="item.dictCode"
                  :label="item.dictName"
                  :value="item.dictCode"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="审核意见:" prop="reviewAdvice">
              <el-input
                v-model="formData.reviewAdvice"
                maxlength="1000"
                show-word-limit
                :autosize="{ minRows: 4, maxRows: 4}"
                type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="closeDialog">取 消</el-button>
        <el-button size="mini" type="primary" @click="submitAudit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { otherFiltersItem } from '@/utils'
import { getDictByPatchType } from '@/api/dataDict'
import { submitSelect, terminalSelect, saveAudit } from '@/api/shopAddEva'

export default {
  name: 'List',
  components: { },
  props: {
    type: {
      type: String,
      default: ''
    },
    activeType: {
      type: String,
      default: ''
    },
    noRequest: {
      type: Boolean,
      default: false
    },
    serachFilters: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      exportVisible: false,
      auditRules: {
        reviewResult: [
          { required: true, message: '请选择审核结果', trigger: 'blur' }
        ],
        reviewAdvice: [
          { required: false, message: '请填写审核意见', trigger: 'blur' }
        ]
      },
      handlefilters: [],
      formData: { id: '', reviewResult: '', reviewAdvice: '', state: '' }, // 审核表单
      auditOptions: [], // 审核意见下拉列表
      auditVisible: false, // 审核弹窗
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/shopLocationEval/page`,
        buttonGroupCode: 'default',
        hideSearchBar: true,
        tabIndex: 0,
        pageSize: 10,
        order: 'desc',
        sort: 'createTime',
        // 表格字段动态配置
        setting: [
          {
            prop: 'locationApplyCode',
            label: '申请编号',
            minWidth: '120',
            className: 'btn-green',
            isButton: true,
            clickFun: this.handleDetail
          },
          {
            prop: 'state',
            label: '选址评估进度',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'SHOP_LOCATION_EVAL_STATE'
            },
            minWidth: '125'
          },
          {
            prop: 'officeName',
            label: '办事处',
            minWidth: '90'
          },
          {
            prop: 'officeNature',
            label: '办事处性质',
            minWidth: '110'
          },

          {
            prop: 'marketSubdType',
            label: '门店建设类型',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'CONST_TYPE'
            },
            minWidth: '110'
          },
          {
            prop: 'businessType',
            label: '商家类型',
            propEnum: {
              domainCode: 'marketing',
              appCode: 'slm',
              dictTypeCode: 'BIZMAN_TYPE'
            },
            minWidth: '110'
          },
          {
            prop: 'customerName',
            label: '经销商姓名',
            minWidth: '110'
          },
          {
            prop: 'customerPhone',
            label: '经销商电话',
            minWidth: '110'
          },
          {
            prop: 'shopAddress',
            label: '卖场详细地址',
            minWidth: '120'
          }
        ]
      },
      tableSelected: [],
      typeFilters: [],
      activeDataId: '',
      state: '',

      id: '',
      loading: false
    }
  },
  computed: {
    otherFilters() {
      return [...this.serachFilters, ...this.typeFilters]
    },
    selectedIds() {
      return this.tableSelected.map(row => {
        return row.id
      })
    },
    exportAllConfig() {
      return [{
        code: 'export',
        name: '门店选址评估',
        dataApi: '/slm-admin/api/v1/shopLocationEval/export?type=0',
        selectedRows: this.tableSelected,
        paramsRaw: {},
        headers: { 'Permission-perCode': 'storeaddeva' },
        filtersRaw: this.otherFilters,
        queryField: 'id'
      }]
    }
  },
  watch: {
    type: {
      handler(v) {
        this.setOtherFilters(v)
      },
      immediate: true
    },
    serachFilters: {
      handler(v) {
        if (this.activeType !== this.type) return
        this.refreshTable('')
      }
    }
  },
  activated() {
    if (this.ready && this.refreshTable) {
      this.refreshTable()
    }
  },
  deactivated() {
    this.ready = true
  },
  created() {
    this.getDictByPatchTypeAll()
  },
  methods: {

    selectionChange(v) {
      this.tableSelected = v
    },

    // 导出
    handleExport() {
      this.exportVisible = true
    },

    // 设置过滤条件
    setOtherFilters(v) {
      switch (v) {
        case 'all':
          this.typeFilters = []
          break
        case 'submit':
          // 显示“已保存”
          this.typeFilters = [otherFiltersItem('state', 'A', '=')]
          break
        case 'audit':
          // 显示“已提交”
          this.typeFilters = [otherFiltersItem('state', 'B', '=')]
          break
        case 'fileMaintenance':
          // 显示“已审核”
          this.typeFilters = [otherFiltersItem('state', 'C', '=')]
          break
      }
    },
    changeresult(data) {
      if (data !== 'A') {
        this.auditRules.reviewAdvice[0].required = true
      } else {
        this.auditRules.reviewAdvice[0].required = false
      }
    },
    async getDictByPatchTypeAll() {
      const { LOCATION_EVAL_REVIEW_RESULT } = await getDictByPatchType(['LOCATION_EVAL_REVIEW_RESULT'])
      this.auditOptions = LOCATION_EVAL_REVIEW_RESULT
    },
    // 刷新表格
    refreshTable(v = 'onPage') {
      this.$nextTick(() => {
        this.$refs.cTableBox.initTableData(v)
      })
    },

    // 导出成功
    handleExportSuccess() {
      this.$message.success('导出成功！')
    },
    // 导入成功
    handleImportSuccess() {
      this.$message.success('导入成功！')
    },
    // 新增/编辑
    handleEdit(data) {
      if (data === '2') {
        if (!this.singleJudge(this.tableSelected, '编辑', true)) {
          return
        }
        if (this.tableSelected[0].state === 'A') {
          this.$router.push({ name: 'EditStoreAdd', query: { id: this.tableSelected[0].id }})
        } else {
          this.$message.warning('已保存的数据才能编辑!')
        }
      } else {
        this.$router.push({ name: 'EditStoreAdd' })
      }
    },
    handleDetail(data) {
      this.$router.push({ name: 'DetailStoreAdd', query: { id: data.id }})
      // this.activeDataId = data.id
      // this.showDetail = true
    },
    // 档案维护
    handlefileMain() {
      if (!this.singleJudge(this.tableSelected, '维护', true)) {
        return
      }
      this.$router.push({ name: 'FileMaintain', query: { id: this.tableSelected[0].id, state: this.tableSelected[0].state }})
    },
    // 提交
    handleSubmit() {
      if (!this.singleJudge(this.tableSelected, '提交', false)) {
        return
      }
      const arrTemp = this.tableSelected.filter(row => { row.state !== 'A' })
      if (arrTemp.length > 0) {
        this.$message.warning('所选项均为已保存时，才能提交!')
        return
      }
      this.$confirm(`是否确认将勾选的【${this.tableSelected.length}条】数据提交审核?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用接口执行提交
        submitSelect(this.selectedIds).then(res => {
          if (res.success === 1) {
            this.$message({
              message: res.msg || '提交成功',
              type: 'success'
            })
            this.refreshTable()
          }
        })
      }).catch(() => {})
    },
    // 终止
    handleTeminal() {
      if (!this.singleJudge(this.tableSelected, '终止', false)) {
        return
      }
      this.$confirm(`是否确认终止勾选的【${this.tableSelected.length}条】数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用接口执行终止
        terminalSelect(this.selectedIds).then(res => {
          if (res.success === 1) {
            this.$message({
              message: res.msg || '终止成功',
              type: 'success'
            })
            this.refreshTable()
          }
        })
      }).catch(() => {})
    },
    // 审核
    handleAudit() {
      if (!this.singleJudge(this.tableSelected, '审核', true)) {
        return
      }
      if (this.tableSelected[0].state !== 'B') {
        this.$message.warning('已提交的数据才能审核!')
        return
      }

      if (this.tableSelected[0].id) {
        this.formData.id = this.tableSelected[0].id
        this.formData.state = this.tableSelected[0].state
        this.auditVisible = true
      }
    },
    closeDialog() {
      this.auditVisible = false
      this.clearForm()
    },
    clearForm() {
      this.formData = {
        id: '',
        reviewResult: '',
        reviewAdvice: '',
        state: ''
      }
    },
    // 设置表格多选行高亮
    tableRowClassName({ row, rowIndex }) {
      const filterArr = this.selectedRows.filter(item => item.id === row.id)
      return filterArr.length > 0 ? 'selected-highlight' : ''
    },
    // 提交审核意见
    submitAudit() {
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          saveAudit(this.formData).then(res => {
            if (res.success === 1) {
              if (this.formData.reviewResult === 'C') { // 不符合建店标准
                this.$message.warning('已终止')
              }
              if (this.formData.reviewResult === 'B') { // 退回修改
                this.$message.warning('已退回保存')
              } else {
                this.$message({
                  message: '审核成功',
                  type: 'success'
                })
              }
              this.refreshTable()
              this.closeDialog()
            }
          }).catch(() => {
          })
        }
      })
    },
    clearSearch() {

    },
    // 获取搜索条件
    handleSearch(data) {
      this.handlefilters = [...data.filtersRaw]
    }
  }
}
</script>
